<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2018/1/26
 * Time: 14:43
 */

namespace Admin\Controller;
use Think\Controller;

class LoginController extends Controller
{
    //登录页面
    public function login(){
        if ($_SESSION['phone'] && $_SESSION['id']){
            $info = D('Admin');
            $id=$info->where(['phone'=>$_SESSION['phone'],'id'=>$_SESSION['id']])->getfield('id');
            if(!empty($id)){
                $this->redirect('Index/index');
                die;
            }
        }
        $this->display();
    }
    /**
     * 用户登录验证
     */
    public function get_login()
    {
        if (!empty($_POST)){
            $info = D('Admin');
            $phone = I('phone');
            $pwd = set_pwd(I('pwd'), I('phone'));
          
            $res = $info->check_login($phone, $pwd);

            //IP限制  外包:183.199.193.174,120.9.81.84
//            $ip_arr = array('122.235.172.65','122.234.176.117','36.24.73.179','115.196.184.33','122.234.181.22','120.9.81.84','183.199.193.174','120.9.81.84','183.129.70.90','115.196.184.28','183.134.166.102', '122.234.180.54', '115.218.237.128','36.24.72.141', '183.129.71.48','122.235.172.140','183.129.68.29');
//            $ip = getIP();
//            if (!in_array($ip, $ip_arr)) {
//                $this->ajax('1002', 'IP非法! 请联系管理员', 'error');
//                die;
//            }

            if ($res) {
                session('id', $res['id']);
                session('phone', $res['phone']);
                session('name', $res['name']);
                session('role_id', $res['role_id']);
                session('out_kf_id', $res['out_kf_id']);
                session('agent', $res['agent']);
                session('kf_manager', $res['kf_manager']);
                session('login_time', date('Y-m-d H:i:s', time()));
                addlog($_SESSION['id']);
                $this->ajax('1001', '登录成功');
            } else {
                $this->ajax('1002', '用户名或者密码错误', 'error');
            }
        }
    }


    /**
     * 退出登录
     */
    public function logout()
    {
        $str = array('aid' => $_SESSION['id'], 'content' => '退出登录', 'ctime' => time());
        $record = M('admin_log', '', 'KEFU')->add($str);

        session(null);
        $this->redirect('/login');
    }


    /**
     * @param $code 错误码 1001成功 1002失败
     * @param $result 详细信息
     * @param string $r 为error的时候表示返回错误信息
     * @return bool
     */

    public function ajax($code, $result, $r = '')
    {
        if (empty($r)) {
            $this->ajaxReturn(['code' => $code, 'result' => $result]);
        } else {
            $this->ajaxReturn(['code' => $code, 'result' => $result]);
            return false;
        }
    }

    public function _empty()
    {
        $this->redirect('Alerterror/error404');
    }

}